﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

using SerialPortListener;

using XHouse.MessageQueueEngine.Interfaces;
using XHouse.Model.Message;

namespace XHouse.MessageQueueEngine
{
    /// <summary>
    /// The message manager.
    /// </summary>
    public class MessageManager : IMessageManager
    {
        /// <summary>
        /// The _serial port helper.
        /// </summary>
        private ISerialPortHelper _serialPortHelper;

        private IInbox _inbox;

        private IOutbox _outbox;

        private Thread outboxThread;

        private bool onActivity;
        /// <summary>
        /// Initializes a new instance of the <see cref="MessageManager"/> class.
        /// </summary>
        /// <param name="serialPortHelper">
        /// The serial port helper.
        /// </param>
        public MessageManager(ISerialPortHelper serialPortHelper, IInbox inbox, IOutbox outbox)
        {
            _serialPortHelper = serialPortHelper;
            _inbox = inbox;
            _outbox = outbox;

            _outbox.NewMessage += this.PussMessage;

            //Asocio el ExtractMessage al evento de lectura del Helper del puerto
            this._serialPortHelper.Lectura += this.ExtractMessage;
        }

        /// <summary>
        /// The start comunication.
        /// </summary>
        /// <exception cref="NotImplementedException">
        /// </exception>
        public bool StartComunication()
        {
            _serialPortHelper.DetectModule();
           
            onActivity = true;

            return true;
        }

        /// <summary>
        /// The stop comunication.
        /// </summary>
        /// <exception cref="NotImplementedException">
        /// </exception>
        public bool StopComunication()
        {
            _serialPortHelper.ClosePort();
            return true;
        }

        private void ExtractMessage(object sender, EventArgs e)
        {
            var txt = _serialPortHelper.ReadExisting();
            

            if (txt.Length >= 12)
            {
                var message = new Message18();
                message.serie = txt.Substring(0, 4);
                message.header = txt.Substring(4, 2);
                message.module = txt.Substring(6, 2);
                message.port = txt.Substring(8, 2);
                message.data = txt.Substring(10, 2);

                //Lo guardo en la Bandeja de Entrada
                _inbox.PutMessage(message);
            }
        }

        private void PussMessage(object sender, EventArgs e)
        {
            //obtengo el ultimo mensaje
            var message = _outbox.GetNextMessage();

            
            _serialPortHelper.WritePort(message.allData);
        }
    }
}
